/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Administrator
 */
public class FiscaleValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object nome) throws ValidatorException {

        if (!(nome instanceof String)) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Errore irreversibile");
            throw new ValidatorException(message);
        }
        String name = (String) nome;
        //verifico che non sia vuoto
        if (name.length() == 0) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Devi inserire il tuo Codice Fiscale");
            throw new ValidatorException(message);
        }
        //verifico che sia superiore a 3
        if (name.length() < 16) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Il Codice Fiscale deve avere 16 cifre");
            throw new ValidatorException(message);
        }
        String regex = "[a-zA-Z]{6}\\d\\d[a-zA-Z]\\d\\d[a-zA-Z]\\d\\d\\d[a-zA-Z]";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(name);

        if (!matcher.matches()) {
            FacesMessage message = new FacesMessage();
            message.setSummary("* Formato Codice Fiscale non valido");
            throw new ValidatorException(message);
        }
    }
}
